package com.ybear.citypickerview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

public class DialogRecyclerView extends androidx.recyclerview.widget.RecyclerView {
    public interface OnScrollStateListener {
        void onScrollState(STATE state, int action, int dy, int oldY);
    }

    public enum STATE { TOP, SCROLL, BOTTOM }

    private OnScrollStateListener mOnScrollStateListener;

    private STATE mState;
    private int oldScrollY;

    public DialogRecyclerView(@NonNull Context context) {
        this(context, null);
    }

    public DialogRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DialogRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onScrolled(int dx, int dy) {
        super.onScrolled(dx, dy);
        //处理滑动状态
        doScrollState();
    }

    /**
     * 处理滑动状态
     */
    private void doScrollState() {
        LinearLayoutManager llManage;
        if( mOnScrollStateListener == null ) return;
        if( !( getLayoutManager() instanceof LinearLayoutManager ) ) return;
        llManage = (LinearLayoutManager) getLayoutManager();
        if( llManage == null ) return;
        int first = llManage.findFirstCompletelyVisibleItemPosition();
        int last = llManage.getItemCount() - llManage.findLastCompletelyVisibleItemPosition() - 1;
        mState = first == 0 ? STATE.TOP : last == 0 ? STATE.BOTTOM : STATE.SCROLL;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int y = (int) ev.getY();
        if( mOnScrollStateListener != null ) {
            mOnScrollStateListener.onScrollState(mState, ev.getAction(), y, oldScrollY);
            oldScrollY = y;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 设置滑动状态事件监听器
     * @param listener  监听器
     */
    public void setOnScrollStateListener(OnScrollStateListener listener) {
        mOnScrollStateListener = listener;
    }
}
